package com.zyf.project.capchain.blockchain.utils;

import com.zyf.project.capchain.blockchain.model.Block;
import com.zyf.project.capchain.blockchain.model.Transaction;
import lombok.Data;
import org.java_websocket.WebSocket;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author Zhou Yifan
 */
@Data
@Component
@PropertySource("classpath:blockchain.properties")
@ConfigurationProperties(prefix = "block")
public class BlockCache {

    /**
     * 当前节点的区块链结构
     */
    private List<Block> blockChain = new CopyOnWriteArrayList<>();

    /**
     * 已打包保存的业务数据集合
     */
    private List<Transaction> packedTransactions = new CopyOnWriteArrayList<>();

    /**
     * 当前节点的socket对象
     */
    private List<WebSocket> socketsList = new CopyOnWriteArrayList<>();

    /**
     * 挖矿的难度系数
     */
    @Value("${block.difficulty}")
    private int difficulty;

    /**
     * 当前节点p2pserver端口号
     */
    @Value("${block.p2pport}")
    private int p2pport;

    /**
     * 要连接的节点地址
     */
    @Value("${block.address}")
    private String address;

    /**
     * 获取最新的区块，即当前链上最后一个区块
     *
     * @return 最新的区块
     */
    public Block getLatestBlock() {
        return !blockChain.isEmpty() ? blockChain.get(blockChain.size() - 1) : null;
    }


}
